package hn.cch.microservice.service_consumer_properties.controller;


import hn.cch.microservice.service_consumer_properties.entity.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.PropertySource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

//加载配置文件路径
@PropertySource(value = {"classpath:application.properties"})
@RestController
public class UserController {

    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    // 读取配置文件参数
    // @Value(value = "${rest.user.url}")
    // private String restUserUrl;

    @Value(value = "${service.instance.name}")
    private String serviceInstanceName;


    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private LoadBalancerClient loadBalancerClient;


    @Bean
    @LoadBalanced
    public RestTemplate restTemplate() {
        RestTemplate restTemplate = new RestTemplate();
        return restTemplate;
    }

    @GetMapping(value = "/{id}")
    public User user(@PathVariable Long id) {
        return restTemplate.getForObject("http://" + serviceInstanceName + "/" + id, User.class);
    }

    @GetMapping(value = "choose")
    public void choose(){
        ServiceInstance serviceInstance = loadBalancerClient.choose(serviceInstanceName);
        logger.info("{}={}:{}", serviceInstance.getServiceId(), serviceInstance.getHost(), serviceInstance.getPort());
    }
}
